﻿using FeiShu.IService.Common;
using Microsoft.Extensions.Configuration;
using System;
using System.Net.Http;
using SSharing.Frameworks.NetCore.Common.Extends;
using Microsoft.Extensions.Caching.Memory;
using FeiShu.Adapter;
using FeiShu.Entity.Adapter.FeiShuWork;
using Microsoft.Extensions.Logging;
using FeiShu.Common.Helpers;

namespace FeiShu.Service.Common
{
    /// <summary>
    /// 公共服务
    /// </summary>
    public class CommonService : ICommonService
    {
        private readonly FeiShuWorkAdapter _feiShuWorkAdapter;
        private readonly IMemoryCache _memoryCache;
        private readonly static object lockObj = new object();
        private readonly string AppId;

        public CommonService(IHttpClientFactory httpclient, IMemoryCache memoryCache, ILogger<CommonService> logger)
        {
            _feiShuWorkAdapter = new FeiShuWorkAdapter(httpclient, logger);
            _memoryCache = memoryCache;
            IConfigurationBuilder builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);//reloadOnChange:true当配置更新了程序自动更新
            builder.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true);
            IConfigurationRoot configRoot = builder.Build();
            var feishuSection = configRoot.GetSection("FEISHU");
            AppId = feishuSection["AppID"];
        }

        /// <summary>
        /// 获取access_token
        /// </summary>
        /// <returns></returns>
        public AccessTokenResponse GetAccessToken()
        {
            AccessTokenResponse result = GetCache();
            if (result == null)
            {
                lock (lockObj)
                {
                    //从缓存重新获取
                    result = GetCache();
                    if (result == null)
                    {
                        var getTokenRS = _feiShuWorkAdapter.GetAccessToken().ToJson();
                        if (!getTokenRS.IsNullOrEmpty())
                        {
                            //序列化和缓存
                            result = getTokenRS.FromJson<AccessTokenResponse>();
                            SetCache(result);
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 刷新access token
        /// </summary>
        /// <returns></returns>
        public bool RefreshAccessToken()
        {
            var cacheKey = CacheHelper.GetAccessTokenKey(AppId);
            _memoryCache.Remove(cacheKey);
            return true;
        }

        #region Private method
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <returns></returns>
        private AccessTokenResponse GetCache()
        {
            AccessTokenResponse result = null;

            var cacheKey = CacheHelper.GetAccessTokenKey(AppId);
            var cacheValue = _memoryCache.Get(cacheKey);
            if (cacheValue != null)
            {
                result = (AccessTokenResponse)cacheValue;
            }

            return result;
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="cacheValue"></param>
        private void SetCache(AccessTokenResponse cacheValue)
        {
            var cacheKey = CacheHelper.GetAccessTokenKey(AppId);
            _memoryCache.Set(cacheKey, cacheValue, DateTimeOffset.Now.AddMinutes(120));
        }
        #endregion
    }
}
